import React, { useEffect, useState } from "react";
import { Button, Popconfirm, Space, Modal, Form, Input } from "antd";
import useCloseLoadingOnMount from "../../../utils/hook/useCloseLoadingOnMount";
import MyTemplate1 from "../../shared/myTemplate1";
import { useNavigate } from "react-router-dom";
import dictionaryTypesApi from "../../../apis/dictionaryTypesApi";
import { promptResult } from "../../../utils/common";

const DictionaryTypeManage = () => {
  useCloseLoadingOnMount();
  const [open, setOpen] = useState(false);
  const [loading, setLoading] = useState(false);
  const [dataSource, setDataSource] = useState([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
    key: "",
  });
  const [flag, setFlag] = useState(false);
  const [form] = Form.useForm();
  const navigate = useNavigate();

  const bind = async () => {
    setLoading(true);
    const response = await dictionaryTypesApi.getDictionaryTypesPagination({
      page: pagination.current,
      limit: pagination.pageSize,
      key: pagination.key,
    });
    setPagination({ ...pagination, total: response.data.total });
    setDataSource(response.data.data);
    setLoading(false);
  };

  // 监听分页对象属性变化，当变化时进行分页
  useEffect(() => {
    bind();
  }, [pagination.current]);

  useEffect(() => {
    if (flag) {
      if (pagination.current != 1) {
        setPagination({ ...pagination, current: 1 });
      } else {
        bind();
      }
    }
    setFlag(true);
  }, [pagination.pageSize, pagination.key]);

  // 初始化加载
  useEffect(() => {
    const fetchData = async () => {
      await bind();
    };
    fetchData();
  }, []);

  const columns = [
    {
      title: "编号",
      dataIndex: "id",
      key: "id",
    },
    {
      title: "名称",
      dataIndex: "name",
      key: "name",
    },
    {
      title: "查询键值",
      dataIndex: "key",
      key: "key",
    },
    {
      title: "描述",
      dataIndex: "description",
      key: "description",
    },
    {
      title: "创建时间",
      dataIndex: "createTimeStr",
      key: "createTimeStr",
    },
    {
      title: "修改时间",
      dataIndex: "updateTimeStr",
      key: "updateTimeStr",
    },
    {
      title: "操作",
      key: "action",
      fixed: "right",
      render: (_, record) => (
        <Space size="middle">
          <Button
            color="geekblue"
            variant="filled"
            onClick={() => handleDetail(record.id)}
          >
            详情
          </Button>
          <Popconfirm
            title="删除字典类别"
            description={`你确定要删除字典类别"${record.name}(${record.key})"吗?`}
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button color="red" variant="filled">
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  const handleDetail = (id) => {
    navigate("detail/" + id);
  };

  const handleDelete = async (id) => {
    await promptResult(
      await dictionaryTypesApi.deleteDictionaryTypes(id),
      bind
    );
  };

  const hideModal = () => {
    setOpen(false);
  };

  const handleAdd = () => {
    setOpen(true);
  };

  const handleSearch = (e) => {
    setPagination({ ...pagination, key: e.target.value });
  };

  const onFinish = async (values) => {
    promptResult(
      await dictionaryTypesApi.addDictionaryTypes(values),
      bind,
      hideModal
    );
  };

  const addDictionaryType = () => {
    form.submit();
  };

  return (
    <>
      <MyTemplate1
        searchProps={{
          placeholder: "搜索字典类别名称",
          onChange: handleSearch,
        }}
        addButtonProps={{
          text: "新增字典类别",
          onClick: handleAdd,
        }}
        columns={columns}
        dataSource={dataSource}
        loading={loading}
        pagination={pagination}
        onPageChange={(page, pageSize) => {
          setPagination({
            ...pagination,
            current: page,
            pageSize,
          });
        }}
      />
      <Modal
        title="添加字典类别"
        open={open}
        onOk={addDictionaryType}
        onCancel={hideModal}
        okText="提交"
        cancelText="取消"
      >
        <Form
          form={form}
          name="editDictionaryType"
          onFinish={onFinish}
          scrollToFirstError={true}
          labelCol={{ span: 3, offset: 0 }}
        >
          <Form.Item
            name="name"
            label="名称"
            rules={[{ required: true, message: "请输入名称" }]}
          >
            <Input placeholder="名称" />
          </Form.Item>
          <Form.Item
            name="key"
            label="键值"
            rules={[{ required: true, message: "请输入键值" }]}
          >
            <Input placeholder="键值" />
          </Form.Item>
          <Form.Item
            name="description"
            label="描述"
            rules={[{ required: true, message: "请输入描述" }]}
          >
            <Input.TextArea placeholder="描述" />
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
};

export default DictionaryTypeManage;
